package interview.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.*;
import java.util.stream.DoubleStream;

/**
 * 线程池获取返回值
 *
 * @Author: cctv
 * @Date: 2019/5/17 11:10
 */
public class ThreadPoolDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        ExecutorService threadPool = Executors.newCachedThreadPool();
//        Future<String> future = threadPool.submit(new MyCallable());
//        if(!future.isDone()){
//            System.out.println("Task has not finished, please wait!");
//        }
//        try {
//            System.out.println("task return :"+future.get());
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//        finally {
//            threadPool.shutdown();
//        }

//        ExecutorService tp =  new ThreadPoolExecutor(0, 100,
//                60L, TimeUnit.SECONDS,
////                new SynchronousQueue<Runnable>()
//                new LinkedBlockingQueue<Runnable>()
//        );
//
//        Future future = tp.submit(new MyCallable());
//        tp.shutdown();
//        System.out.println("task return :"+future.get());

        // 使用Guava的ThreadFactoryBuilder
        int taskNum = 100;
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();
        ExecutorService executorService = new ThreadPoolExecutor(
                5,
                taskNum / 2,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(taskNum / 2 - 1),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy());

        ArrayList<Future> futureList = new ArrayList<>(taskNum);
        for (int i = 0; i < taskNum; i++) {
            try {
                futureList.add(executorService.submit(new MyCallable(i)));
            } catch (RejectedExecutionException e) {
                System.out.println("看到这个异常表示编号[" + i +
                        "]号任务被拒绝了，原因是线程数到达最大值了，队列也满了。" + e.getMessage());
//                // 重试机制
//                Thread.sleep(1000);
//                futureList.add(executorService.submit(new MyCallable(i)));
            }
        }
        executorService.shutdown();
        System.out.println("得到结果的数量是：" + futureList.size());
        for (int i = 0; i < futureList.size(); i++) {
            System.out.println(futureList.get(i).get());
        }


    }
}
